06. Adding Markers

L4 A05 Adding Markers

Reference Documentation

By default, the onMapReady() callback includes code that places a marker in Sydney, Australia, where Google Maps was created. The default callback also animates the map to pan to Sydney. In this step, you make the map’s camera move to your home, zoom to a level you specify and place a marker there.

  1. In the onMapReady() method, remove the code that places the marker in Sydney and moves the camera. This is what your method should look like now.
override fun onMapReady(googleMap: GoogleMap) {
   map = googleMap

}
  1. Find the latitude and longitude of your home by following these instructions.
  2. Create a value for the latitude and a value for the longitude and input their float values.
val latitude = 37.422160
val longitude = -122.084270
  1. Create a new LatLng object called home. In the LatLng object, use the values you just created.
val homeLatLng = LatLng(latitude, longitude)
  1. Move the camera to home by calling the moveCamera() function on the GoogleMap object and pass in a CameraUpdate object using CameraUpdateFactory.newLatLngZoom(). Create a val for how zoomed in you want to be on the map.

The zoom level controls how zoomed in you are on the map. The following list gives you an idea of what level of detail each level of zoom shows:

  • 1: World
  • 5: Landmass/continent
  • 10: City
  • 15: Streets
  • 20: Buildings

Pass in the home object and a float for how zoomed in you want it to be.

val zoomLevel = 15f
map.moveCamera(CameraUpdateFactory.newLatLngZoom(homeLatLng, zoomLevel))
  1. Add a marker to the map at your home.
map.addMarker(MarkerOptions().position(homeLatLng))

The method should look like this.

override fun onMapReady(googleMap: GoogleMap) {
   map = googleMap

   //These coordinates represent the latitude and longitude of the Googleplex.
   val latitude = 37.422160
   val longitude = -122.084270
   val zoomLevel = 15f

   val homeLatLng = LatLng(latitude, longitude)
   map.moveCamera(CameraUpdateFactory.newLatLngZoom(homeLatLng, zoomLevel))
   map.addMarker(MarkerOptions().position(homeLatLng))
}
  1. Run the app. The map should pan to your home, zoom into the desired level and place a marker on your home.